package hl.crazy_java.chapter_16;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

/**
 * 
 * @author Liu Huan
 */


class Producer extends Thread {
    // 定义一个 阻塞队列引用变量 指向 传进来的对象引用
    private BlockingQueue<String> bq;
    public Producer(BlockingQueue<String> bq) {
        this.bq = bq;
    }

    @Override
    public void run() {
        for (int i = 0; i < 99; i++) {
            try {
                System.out.println(getName() + "准备生产");
                Thread.sleep(200);
                if (bq.isEmpty()) {
                    bq.put("java");
                    System.out.println(getName() + "生产成功，剩余：" + bq);
                } else {
                    System.out.println(getName() + "阻塞");
                    bq.put("java");
                }

            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

class Consume extends Thread {
    private BlockingQueue<String> bq;
    public Consume(BlockingQueue<String> bq) {
        this.bq = bq;
    }

    @Override
    public void run() {
        for (int i = 0; i < 4; i++) {
            try {
                System.out.println(getName() + "准备消费");
                Thread.sleep(200);
                if (bq.isEmpty()) {
                    System.out.println(getName() + "阻塞");
                    bq.take();
                } else {
                    bq.take();
                    System.out.println(getName() + "消费成功，还剩：" + bq);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

public class BlockingQueueTest {
    public static void main(String[] args) throws InterruptedException {

        BlockingQueue<String> bq = new ArrayBlockingQueue<>(1);

        new Producer(bq).start();
       // new Producer(bq).start();

        new Consume(bq).start();
    }
}
